package top.ranzhang.service.impl;



import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import top.ranzhang.bean.dto.AddCourseDTO;
import top.ranzhang.bean.dto.UpadteCourseDTO;
import top.ranzhang.bean.entity.Course;
import top.ranzhang.bean.vo.AdminCourseVO;
import top.ranzhang.bean.vo.CourseTableVO;
import top.ranzhang.constant.ShowDateCountConstant;
import top.ranzhang.constant.DateConstant;
import top.ranzhang.mapper.CourseMapper;
import top.ranzhang.service.ICourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ran
 * @since 2025-04-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    private final CourseMapper courseMapper;

    /**
     * 添加课程信息
     * @param addCourseDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ToSave(AddCourseDTO addCourseDTO) {
        Course course = new Course();
        BeanUtils.copyProperties(addCourseDTO, course);
        save(course);
        courseMapper.insertChild(course.getId(), addCourseDTO.getChildId());
        courseMapper.insertCoash(course.getId(), addCourseDTO.getCoashId());
    }

    /**
     * 删除课程信息
     * @param id
     */
    @Override
    public void ToRemove(Integer id) {
        removeById(id);
        courseMapper.ChildRemove(id);
        courseMapper.CoashRemove(id);
    }

    /**
     * 修改课程信息
     * @param upadteCourseDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void ToUpdate(UpadteCourseDTO upadteCourseDTO) {
        Course course = new Course();
        BeanUtils.copyProperties(upadteCourseDTO, course);
        updateById(course);
        courseMapper.ChildRemove(upadteCourseDTO.getId());
        courseMapper.CoashRemove(upadteCourseDTO.getId());
        courseMapper.insertChild(upadteCourseDTO.getId(), upadteCourseDTO.getChildId());
        courseMapper.insertCoash(upadteCourseDTO.getId(), upadteCourseDTO.getCoashId());
    }

    @Override
    public AdminCourseVO ToGetById(Integer id) {
        AdminCourseVO adminCourseVO = courseMapper.ToGetById(id);
        adminCourseVO.setEndTime(adminCourseVO.getStartTime().plusMinutes(adminCourseVO.getLessonLen()));
        return adminCourseVO;
    }

    /**
     * 获取课程列表
     * @return
     */
//    @Override
//    public CourseTableVO ToList() {
//        int count = ShowDateCountConstant.DAY_COUNT;
//        // 获取当前日期
//        LocalDate now = LocalDate.now();
//        List<LocalDate> dateList = new ArrayList<>();
//        List<String> weekList = new ArrayList<>();
//        List<List<AdminCourseVO>> courseList = new ArrayList<>();
//        // 获取前7天的日期
//        while(count-- >0){
//            dateList.add(now);
//            // 获取星期几
//            int value = now.getDayOfWeek().getValue();
//            weekList.add(DateConstant.weekDays[value]);
//            // 获取当天的开始时间和结束时间
//            LocalDateTime start = now.atTime(LocalTime.MIN);
//            LocalDateTime end = now.atTime(LocalTime.MAX);
//            // 获取当天的课程列表
//            List<AdminCourseVO> courseNowList = courseMapper.TOGetListNow(start,end);
//            // 如果当天没有课程，则添加空列表
//            if(courseNowList == null || courseNowList.size() == 0){
//                courseList.add(null);
//            }else{
//                courseNowList.stream()
//                        .forEach(item -> {
//                            // 计算结束时间
//                                item.setEndTime(item.getStartTime().plusMinutes(item.getLessonLen()));
//                                // 计算距离8点的时间
//                                item.setDistanceToEight(
//                                        Duration.between(
//                                                DateConstant.DayStartDay,
//                                                item.getStartTime().toLocalTime())
//                                                .toMinutes()
//                                         );
//                        });
//
//                courseList.add(courseNowList);
//            }
//            // 获取下一天的日期
//            now = now.plusDays(1);
//        }
//        return CourseTableVO.builder()
//                .dateList(dateList)
//                .weekList(weekList)
//                .courseList(courseList)
//                .build();
//    }

    //优化后的获取课程列表
    public CourseTableVO ToList() {
        int count = ShowDateCountConstant.DAY_COUNT;
        LocalDate now = LocalDate.now();
        List<String> dateList = new ArrayList<>(count);
        List<String> weekList = new ArrayList<>(count);
        List<List<AdminCourseVO>> courseList = new ArrayList<>(count);

        // 获取前7天的所有日期范围
        List<Map<String, Object>> timeRanges = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            LocalDateTime start = now.atTime(LocalTime.MIN);
            LocalDateTime end = now.atTime(LocalTime.MAX);
            Map<String, Object> range = new HashMap<>();
            range.put("start", start);
            range.put("end", end);
            timeRanges.add(range);
            now = now.plusDays(1);
        }

        // 批量查询所有课程
        List<AdminCourseVO> allCourses = courseMapper.TOGetListBatch(timeRanges);

        // 按日期分组
        Map<LocalDate, List<AdminCourseVO>> groupedCourses = allCourses.stream()
                .collect(Collectors.groupingBy(course -> course.getStartTime().toLocalDate()));

        // 处理每一天的数据
        now = LocalDate.now(); // 重置为当前日期
        for (int i = 0; i < count; i++) {
            dateList.add(now.getMonth().getValue() + "-" + now.getDayOfMonth());
            int value = now.getDayOfWeek().getValue();
            weekList.add(DateConstant.weekDays[value]);

            // 获取当天的课程列表
            List<AdminCourseVO> courseNowList = groupedCourses.getOrDefault(now, Collections.emptyList());

            if (courseNowList.isEmpty()) {
                courseList.add(null);
            } else {
                // 计算结束时间和距离8点的时间
                for (AdminCourseVO item : courseNowList) {
                    item.setEndTime(item.getStartTime().plusMinutes(item.getLessonLen()));
                    item.setDistanceToEight(
                            Duration.between(DateConstant.DayStartDay, item.getStartTime().toLocalTime())
                                    .toMinutes()
                    );
                }
                courseList.add(courseNowList);
            }

            // 移动到下一天
            now = now.plusDays(1);
        }

        return CourseTableVO.builder()
                .dateList(dateList)
                .weekList(weekList)
                .courseList(courseList)
                .build();
    }

}
